"""Wikipedia tool for the React Agent."""

import wikipedia
from typing import Any, Dict
from .base_tool import BaseTool, ToolResult


class WikipediaTool(BaseTool):
    """Tool for searching and retrieving information from Wikipedia."""
    
    def __init__(self):
        super().__init__(
            name="wikipedia",
            description=self._get_detailed_description()
        )
        # Set Wikipedia language and other settings
        wikipedia.set_lang("en")
    
    def _get_detailed_description(self) -> str:
        """Get detailed description with examples for Wikipedia operations."""
#         return """Search Wikipedia for information about people, places, events, concepts, and general knowledge.
#
# WHAT IT DOES:
# • Searches Wikipedia articles using the provided query
# • Returns article summaries, titles, and URLs
# • Provides factual, encyclopedic information
# • Automatically suggests corrections for misspelled queries
#
# INFORMATION TYPES:
# • People: Scientists, politicians, celebrities, historical figures
#   Examples: "Albert Einstein", "Marie Curie", "Nelson Mandela"
#
# • Places: Countries, cities, landmarks, geographical features
#   Examples: "Paris France", "Mount Everest", "Great Wall of China"
#
# • Events: Historical events, wars, discoveries, accidents
#   Examples: "World War II", "Moon landing", "Renaissance"
#
# • Concepts: Scientific topics, philosophies, technologies
#   Examples: "Quantum mechanics", "Artificial intelligence", "Democracy"
#
# • Organizations: Companies, institutions, governments
#   Examples: "United Nations", "Harvard University", "NASA"
#
# USAGE EXAMPLES:
# - Person lookup: "Stephen Hawking"
# - Place information: "Tokyo Japan"
# - Historical event: "American Civil War"
# - Scientific concept: "Theory of relativity"
# - Current topics: "Climate change"
#
# SEARCH TIPS:
# • Use specific names for better results
# • Include context if term is ambiguous (e.g., "Apple company" vs "Apple fruit")
# • Try alternative spellings if no results found
# • Be concise but descriptive
#
# RETURNED INFORMATION:
# - Article title and summary (3 sentences by default)
# - Wikipedia page URL for full article
# - Related categories and links
# - Auto-corrected search terms if applicable
#
# LIMITATIONS:
# - Only searches English Wikipedia
# - May not have very recent information
# - Some controversial topics may have limited coverage
# - Disambiguation may be needed for common terms"""

        return """在维基百科上搜索有关人物、地点、事件、概念和常识的信息。

功能：
- 使用提供的查询词搜索维基百科文章。
- 返回文章摘要、标题和网址。
- 提供事实性的百科全书信息。
- 自动为拼写错误的查询词提供纠正建议。

信息类型：
- 人物：科学家、政治家、名人、历史人物
  示例：“阿尔伯特·爱因斯坦”、“玛丽·居里”、“纳尔逊·曼德拉”
- 地点：国家、城市、地标、地理特征
  示例：“法国巴黎”、“珠穆朗玛峰”、“中国长城”
- 事件：历史事件、战争、发现、事故
  示例：“第二次世界大战”、“月球登陆”、“文艺复兴”
- 概念：科学主题、哲学、技术
  示例：“量子力学”、“人工智能”、“民主”
- 组织：公司、机构、政府
  示例：“联合国”、“哈佛大学”、“美国国家航空航天局”

使用示例：
- 人物查询：“斯蒂芬·霍金”
- 地点信息：“日本东京”
- 历史事件：“美国内战”
- 科学概念：“相对论”
- 时事话题：“气候变化”

搜索提示：
- 使用具体的名称以获得更好的结果。
- 如果术语有歧义，请包含上下文（例如，“苹果公司”与“苹果果实”）。
- 如果未找到结果，请尝试其他拼写。
- 表述要简洁但具描述性。

返回信息：
- 文章标题和摘要（默认3句话）。
- 完整文章的维基百科页面网址。
- 相关类别和链接。
- 适用时自动纠正的搜索词。

局限性：
- 仅搜索英文维基百科。
- 可能没有非常新的信息。
- 一些有争议的主题可能 coverage 有限。
- 常见术语可能需要消除歧义。"""

    async def execute(self, query: str, **kwargs) -> ToolResult:
        """Execute Wikipedia search and retrieval."""
        try:
            # Get optional parameters
            sentences = kwargs.get("sentences", 3)
            auto_suggest = kwargs.get("auto_suggest", True)
            
            # Search for the page
            try:
                # Get page summary
                summary = wikipedia.summary(
                    query, 
                    sentences=sentences, 
                    auto_suggest=auto_suggest
                )
                
                # Get the page object for additional info
                page = wikipedia.page(query, auto_suggest=auto_suggest)
                
                result_data = {
                    "title": page.title,
                    "summary": summary,
                    "url": page.url,
                    "categories": page.categories[:10] if hasattr(page, 'categories') else [],
                    "links": page.links[:20] if hasattr(page, 'links') else []
                }
                
                return ToolResult(
                    success=True,
                    data=result_data,
                    metadata={
                        "query": query,
                        "sentences": sentences,
                        "auto_suggest": auto_suggest
                    }
                )
                
            except wikipedia.DisambiguationError as e:
                # Handle disambiguation - return options
                options = e.options[:10]  # Limit to first 10 options
                
                return ToolResult(
                    success=False,
                    data={
                        "disambiguation_options": options,
                        "message": f"Multiple pages found for '{query}'. Please be more specific."
                    },
                    error=f"Disambiguation needed for '{query}'"
                )
                
            except wikipedia.PageError:
                # Try to search for similar pages
                try:
                    search_results = wikipedia.search(query, results=5)
                    if search_results:
                        return ToolResult(
                            success=False,
                            data={
                                "search_suggestions": search_results,
                                "message": f"Page '{query}' not found. Here are some suggestions."
                            },
                            error=f"Page '{query}' not found"
                        )
                    else:
                        return ToolResult(
                            success=False,
                            data=None,
                            error=f"No Wikipedia page found for '{query}'"
                        )
                except Exception:
                    return ToolResult(
                        success=False,
                        data=None,
                        error=f"No Wikipedia page found for '{query}'"
                    )
        
        except Exception as e:
            return ToolResult(
                success=False,
                data=None,
                error=f"Wikipedia search failed: {str(e)}"
            )
    
    def get_schema(self) -> Dict[str, Any]:
        """Get the tool's input schema."""
        return {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    # "description": "Search term or topic to look up on Wikipedia"
                    "description": "在维基百科上查找的搜索词或主题"
                },
                "sentences": {
                    "type": "integer",
                    # "description": "Number of sentences to return in summary (default: 3)",
                    "description": "要返回的摘要句子数量（默认值：3）",
                    "default": 3,
                    "minimum": 1,
                    "maximum": 10
                },
                "auto_suggest": {
                    "type": "boolean",
                    # "description": "Whether to use Wikipedia's auto-suggestion feature (default: true)",
                    "description": "是否使用维基百科的自动建议功能（默认值：true）",
                    "default": True
                }
            },
            "required": ["query"]
        }